package com.ldkj.panzh.service.impl;

import cn.hutool.http.HttpRequest;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ldkj.panzh.param.PlcParam;
import com.ldkj.panzh.service.PlcPostService;
import com.ldkj.panzh.vo.PlcVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@Slf4j
@Service
public class PlcPostServiceImpl implements PlcPostService {


    private static final ObjectMapper mapper = new ObjectMapper();
    private static final String DATE_PATTERN = "yyyy-MM-dd HH:mm:ss";

    /**
     * 获取设备PLC信息
     * @param plcParam
     * @return
     * @throws Exception
     */
    @Override
    public PlcVO getEqpPlcInfo(PlcParam plcParam) {
        try {
            String url = buildUrl(plcParam);
//            String requestBody = buildRequestBody(plcParam);
//            String responseBody = sendPostRequest(url, requestBody);
//            PlcVO plcVO = parseResponse(responseBody);
//            plcVO.setPath(plcParam.getPath());
//            return plcVO;
            System.out.println(url);
            return buildPlcVO(plcParam);

        } catch (Exception e) {
            // 可记录日志
            e.printStackTrace();
            return new PlcVO(); // 返回空对象
        }
    }

    /** 构建请求 URL */
    private String buildUrl(PlcParam plcParam) {
        return "http://" + plcParam.getPlcIp() + ":" + plcParam.getPlcHost() + "/openapi/data/latest/flat/kv";
    }

    /** 构建请求体 */
    private String buildRequestBody(PlcParam plcParam) throws JsonProcessingException {
        Map<String, Object> params = new HashMap<>();
        params.put("path", plcParam.getPath());
        params.put("pathHeader", true);
        params.put("withTs", true);
        return mapper.writeValueAsString(params);
    }

    /** 发送 HTTP POST 请求 */
    private String sendPostRequest(String url, String requestBody) {
        return HttpRequest.post(url)
                .header("Content-Type", "application/json")
                .body(requestBody)
                .execute()
                .body();
    }

    /** 解析响应为 PlcVO */
    private PlcVO parseResponse(String responseBody) throws Exception {
        if (responseBody == null || responseBody.isEmpty()) {
            return new PlcVO();
        }

        JsonNode root = mapper.readTree(responseBody);
        if (!"200".equals(root.path("code").asText())) {
            return new PlcVO();
        }

        JsonNode dataNode = root.path("data");
        if (dataNode.isMissingNode() || dataNode.isEmpty()) {
            return new PlcVO();
        }

        Iterator<Map.Entry<String, JsonNode>> fields = dataNode.fields();
        if (!fields.hasNext()) {
            return new PlcVO();
        }

        JsonNode valueObj = fields.next().getValue();
        return buildPlcVO(valueObj);
    }

    /** 构建 PlcVO 对象 */
    private PlcVO buildPlcVO(JsonNode valueObj) {
        PlcVO vo = new PlcVO();
        vo.setValue(valueObj.path("value").isNull() ? null : valueObj.path("value").asText());
        vo.setTime(valueObj.path("time").isNull() ? null : formatTimestamp(valueObj.path("time").asLong()));
        return vo;
    }


    /** 随机VLAUE 具体值 */
    private PlcVO buildPlcVO(PlcParam plcParam) {
        PlcVO vo = new PlcVO();
        // 生成 30 ~ 50 之间的随机数值
        double randomValue = 30 + Math.random() * 20;
        vo.setValue(String.format("%.2f", randomValue));
        // 当前时间
        vo.setTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

        // 设置 path
        vo.setPath(plcParam.getPath());

        return vo;
    }



    /** 时间戳转换为 yyyy-MM-dd HH:mm:ss */
    private String formatTimestamp(long ts) {
        return new SimpleDateFormat(DATE_PATTERN).format(new Date(ts));
    }

}
